//
// Sample application that shows how to use RokkoMVC to get data from the server
// using AJAX. 
//
// PS: This demo assumes you have included jQuery AND Mustache.js in your WordPress theme.
//     How you load those resources is up to you. Normally you'd only load Mustache.js when
//     you load a Javascript resource that would use it to parse some data into a template.
//


/***********************************************************
 * Parse some data into a Mustache.js template and display it
 ***********************************************************/
function displayHelloWorld(pData){
   var html = Mustache.to_html(pData.template, pData);
   $(pData.container).html(html);
}


/***********************************************************
 * @param pContainerEl a reference to some DOM element where you want text displayed. A <div> element would do just fine...
 ***********************************************************/
function init(pContainerEl, pAppUrl, pSiteUrl){
   
   // Specify how many resources we need before moving on. 
   // In this case, a template file and its accompanying data. Both will be loaded async using Rokko MVC.
   var neededResources = 2;
   var totalResources = 0;
   var data = {container: pContainerEl};
   
   // Display a loading message while we get the resources
   $(pContainerEl).text("Loading...");
   
   
   //
   // Get each resource separately
   //

   // Use siteURL and RokkoMVC to get some data
   $.getJSON(pSiteUrl + "?reqTypeAsync=true&reqName=getTablesJSON@Tables", function(res){
      data.tables = res.tables;
      totalResources++;

      // Only proceed if both resources have been loaded
      if (totalResources == neededResources)
         displayHelloWorld(data);
   });
   
   
   // Use appURL to get a static resource directly from the server
   $.get(pAppUrl + "views/js/hello-world.mustache.tmpl", function(res){
      data.template = res;
      totalResources++;
      
      // Only proceed if both resources have been loaded
      if (totalResources == neededResources)
         displayHelloWorld(data);
   });
}


//
// Get the application going...
//
